package com.example.service.impl;

import com.example.common.RequireDataPermission;
import com.example.entity.User;
import com.example.entity.UserRole;
import com.example.mapper.UserMapper;
import com.example.mapper.UserRoleMapper;
import com.example.service.DataPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 数据权限服务实现
 */
@Service
public class DataPermissionServiceImpl implements DataPermissionService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Override
    public boolean hasDataPermission(Long userId, String resourceType, Long resourceId, 
                                   RequireDataPermission.DataPermissionType permissionType) {
        
        switch (permissionType) {
            case SELF_ONLY:
                return checkSelfOnlyPermission(userId, resourceType, resourceId);
            case DEPARTMENT:
                return checkDepartmentPermission(userId, resourceType, resourceId);
            case DEPARTMENT_AND_SUB:
                return checkDepartmentAndSubPermission(userId, resourceType, resourceId);
            case ALL:
                return checkAllPermission(userId);
            case CUSTOM:
                return checkCustomPermission(userId, resourceType, resourceId);
            default:
                return false;
        }
    }
    
    @Override
    public boolean hasUserDataPermission(Long currentUserId, Long targetUserId, 
                                       RequireDataPermission.DataPermissionType permissionType) {
        
        switch (permissionType) {
            case SELF_ONLY:
                return currentUserId.equals(targetUserId);
            case DEPARTMENT:
                return checkSameDepartment(currentUserId, targetUserId);
            case DEPARTMENT_AND_SUB:
                return checkDepartmentAndSub(currentUserId, targetUserId);
            case ALL:
                return checkAllPermission(currentUserId);
            default:
                return false;
        }
    }
    
    @Override
    public String getDataPermissionSql(Long userId, String resourceType, 
                                     RequireDataPermission.DataPermissionType permissionType) {
        
        switch (permissionType) {
            case SELF_ONLY:
                return "user_id = " + userId;
            case DEPARTMENT:
                return getDepartmentSql(userId);
            case DEPARTMENT_AND_SUB:
                return getDepartmentAndSubSql(userId);
            case ALL:
                return "1 = 1"; // 无限制
            default:
                return "1 = 0"; // 无权限
        }
    }
    
    /**
     * 检查只能操作自己数据的权限
     */
    private boolean checkSelfOnlyPermission(Long userId, String resourceType, Long resourceId) {
        if ("user".equals(resourceType)) {
            return userId.equals(resourceId);
        }
        
        // 对于其他资源类型，检查是否为该用户创建的
        // 这里可以根据具体业务逻辑扩展
        return false;
    }
    
    /**
     * 检查部门权限
     */
    private boolean checkDepartmentPermission(Long userId, String resourceType, Long resourceId) {
        // 简化实现：这里应该根据实际的部门表结构来实现
        // 目前先返回true，实际项目中需要查询用户部门信息
        return true;
    }
    
    /**
     * 检查部门及子部门权限
     */
    private boolean checkDepartmentAndSubPermission(Long userId, String resourceType, Long resourceId) {
        // 简化实现：这里应该根据实际的部门表结构来实现
        return true;
    }
    
    /**
     * 检查是否有全部数据权限（通常是管理员）
     */
    private boolean checkAllPermission(Long userId) {
        // 检查用户是否有管理员角色
        List<UserRole> userRoles = userRoleMapper.selectByUserId(userId);
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        
        // 假设角色ID为1的是超级管理员
        return roleIds.contains(1L);
    }
    
    /**
     * 自定义权限检查
     */
    private boolean checkCustomPermission(Long userId, String resourceType, Long resourceId) {
        // 这里可以实现自定义的权限检查逻辑
        return false;
    }
    
    /**
     * 检查是否同部门
     */
    private boolean checkSameDepartment(Long currentUserId, Long targetUserId) {
        // 简化实现：实际项目中需要查询用户部门信息
        return true;
    }
    
    /**
     * 检查部门及子部门
     */
    private boolean checkDepartmentAndSub(Long currentUserId, Long targetUserId) {
        // 简化实现：实际项目中需要查询用户部门信息
        return true;
    }
    
    /**
     * 获取部门权限SQL
     */
    private String getDepartmentSql(Long userId) {
        // 简化实现：实际项目中需要根据用户部门生成SQL
        return "1 = 1";
    }
    
    /**
     * 获取部门及子部门权限SQL
     */
    private String getDepartmentAndSubSql(Long userId) {
        // 简化实现：实际项目中需要根据用户部门生成SQL
        return "1 = 1";
    }
}
